#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager
from utility.api_security import APISecurity
from utility.app_security import AppSecurity
from authlib.jose import jwt
from datetime import datetime, timedelta
import time
from utility.error_code import error_code
from utility import tools
from settings import ODOO_DB, SECRET_KEY
import codecs
import logging

AppSecurity = AppSecurity()
_logger = logging.getLogger(__name__)


class AppUserLoginAPI(Resource):
    """
    验证用户名和密码，并返回登录态token
    :request: get
    :param login: 用户名
    :param password: 密码
    :returns: json string
    """

    _transient_max_hours = 7 * 24  # token失效时间

    @AppSecurity.public_verify()
    def get(self):
        try:
            odoo = OdooManager().get_instance()
            prikey = odoo.env['ir.config_parameter'].get_param('api.rsa.private.key', False)
            prikey = codecs.getdecoder("unicode_escape")(prikey)[0]  # 秘钥恢复转义
            login = tools.rsa_decrypt(request.args['login'], prikey)
            password = tools.rsa_decrypt(request.args['password'], prikey)
            uid = odoo.env['res.users'].authenticate(ODOO_DB, login, password, None)
            user = odoo.env['res.users'].browse(uid)[0]

            # 生成token aud：接收人 uid：接收人id exp：过期时间戳
            header = {'typ': 'JWT', 'alg': 'HS256'}  # 签名算法
            exp_date = datetime.now() + timedelta(seconds=self._transient_max_hours * 3600)
            struct_time = exp_date.timetuple()  # struct_time类型
            exp = int(time.mktime(struct_time))
            payload = {'aud': user.id, 'exp': exp}
            token = jwt.encode(header=header, payload=payload, key=SECRET_KEY)  # byte类型
            return jsonify({'code': 0, 'msg': 'success', 'data': {'token': token.decode()}})
        except AttributeError as e:
            _logger.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            _logger.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class AppUserCheckTokenAPI(Resource):
    """
    根据token校验登录态，用于APP端登录校验
    :request: get
    :param token: Token
    :returns: json string
    """

    @AppSecurity.public_verify()
    def get(self):
        try:
            # token校验
            payload = APISecurity().verify_access_()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})

            return jsonify({'code': 0, 'msg': 'success', 'data': {'user_id': payload['aud']}})
        except AttributeError as e:
            _logger.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            _logger.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class UserInfoAPI(Resource):
    """
    根据获取用户信息
    :request: get
    :returns: json string
    """

    def get(self):
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})

            user_id = payload['aud']
            odoo = OdooManager().get_instance()
            odoo_user = odoo.env['res.users']
            domain = [
                ("id", "=", int(user_id))
            ]
            user_tab = odoo_user.search_read(
                domain,
                [
                    "id", "name", "phone", "id_card"
                ]
            )
            data = {
                "userId": int(user_id),
                "name": "",
                "tel": "",
                "sex": "",
                "idCard": ""
            }
            if user_tab:
                user_data = user_tab[0]
                data["userId"] = user_data["id"]
                if user_data["name"]:
                    data["name"] = user_data["name"]
                if user_data["phone"]:
                    data["tel"] = user_data["phone"]
                if user_data["id_card"]:
                    data["idCard"] = user_data["id_card"]
            return jsonify({'code': 0, 'msg': "success", "data": data})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

